//
//  ARScanning.swift
//  ARScanningDemo
//
//  Created by wanglc on 2018/3/7.
//  Copyright © 2018年 GitHub. All rights reserved.
//

import UIKit

let kBlueLayerColor = kRGBColorFromHex(rgbValue: 0x00BFFF)
let kBlue2LayerColor = kRGBColorFromHex(rgbValue: 0x1EFFEC)
let kWhiteLayerColor = kRGBColorFromHex(rgbValue: 0xFFFFFF)

//十六进制颜色值转化为UIColor
func kRGBColorFromHex(rgbValue: Int) -> UIColor {
    
    return UIColor(red: ((CGFloat((rgbValue & 0xFF0000) >> 16))/255.0),
                   green: ((CGFloat((rgbValue & 0xFF00) >> 8))/255.0),
                   blue: ((CGFloat(rgbValue & 0xFF))/255.0),
                   alpha: 1.0)
}

//汉字转拼音
extension String {
    
    func transformToPinYin() -> NSString {
        
        let mutableString = NSMutableString(string: self)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
//        let string = String(mutableString)
        
        return mutableString.replacingOccurrences(of: " ", with: "") as NSString
    }
}

class ARScanning: NSObject {
    
    var parnentView: UIView?
    var _viewWidth:CGFloat = 0.0
    var _viewheight:CGFloat = 0.0
    
    var outLayer: CALayer?
    let _outLayerRadius: CGFloat = 105.5
    let _outLayerWidth: CGFloat = 1.5
    
    var blueLayer: CALayer?
    let _blueLayerRadius: CGFloat = 92.5
    let _blueLayerWidth: CGFloat = 5.0
    let _triangleLayerRadius: CGFloat = 6.0
    let _triangleLayerWidth: CGFloat = 2.0
    let _shadowRadius: CGFloat = 10.0
    
    var inLayer: CALayer?
    let _inLayerRadius: CGFloat = 77.5
    let _inLayerWidth1: CGFloat = 1.0
    let _inLayerWidth2: CGFloat = 1.5
    
    var whiteLayer: CALayer?
    let _whiteLayerRadius: CGFloat = 92
    let _whiteLayerWidth: CGFloat = 28.0
    
    var centerCircleLayer: CALayer?
    let _centerCircleLayerRadius: CGFloat = 16.5
    
    var centerPointLayer: CALayer?
    let _centerPointLayerRadius: CGFloat = 1.5
    
    var alertLayer: CALayer?
    var pointLayer: CAShapeLayer?
    var polylineLayer: CAShapeLayer?
    var textLayer: CATextLayer?
    var pinyinLayer: CATextLayer?
    
    let animations = ARScanningAnimations()
    
    func drawLayerAt(view: UIView) -> Void {
        
        self.parnentView = view
        _viewWidth = view.frame.size.width
        _viewheight = view.frame.size.height
        
        self.drawOutLayer()
        self.drawBlueLayer()
        self.drawInlayer()
        self.drawWhiteLayer()
        self.drawCenterCircle()
        self.drawCenterPoint()
        self.drawAlertLayer(string: "小苏苏")
    }
    
    //MARK: 图层动画
    
    func startAnimations() -> Void {
        
        self.parnentView?.layer.removeAllAnimations()
        
        self.animations.addScanningAnimationsTo(layer: self.blueLayer!, delayTime: 0.0, animationKey: "BlueLayerScanning")
        self.animations.addScanningAnimationsTo(layer: self.outLayer!, delayTime: 0.034, animationKey: "OutLayerScanning")
        self.animations.addScanningAnimationsTo(layer: self.inLayer!, delayTime: 0.066, animationKey: "InLayerScanning")
        
        self.animations.addScanningAnimationsTo(layer: self.whiteLayer!, delayTime: 0.066, animationKey: "WhiteCircleLayerScanning")
        self.animations.addScanningAnimationsTo(layer: self.centerCircleLayer!, delayTime: 0.066, animationKey: "CenterCircleLayerScanning")
        self.animations.addScanningAnimationsTo(layer: self.centerPointLayer!, delayTime: 0.066, animationKey: "CenterPointLayerScanning")

        Timer.scheduledTimer(withTimeInterval: 1.666, repeats: false) { (Timer) in
            self.scanningEndAnimations()
        }
    }
    
    func scanningEndAnimations() -> Void {
        
        self.animations.addScanningEndAnimations(layer: self.blueLayer!, animationKey: "BlueLayerScanningEnd")
        self.animations.addScanningEndAnimations(layer: self.outLayer!, animationKey: "OutLayerScanningEnd")
        self.animations.addScanningEndAnimations(layer: self.inLayer!, animationKey: "InLayerScanningEnd")

        self.animations.addScanningEndAnimations(layer: self.whiteLayer!, animationKey: "WhiteCircleLayerScanningEnd")
        self.animations.addScanningEndAnimations(layer: self.centerCircleLayer!, animationKey: "CenterCircleLayerScanningEnd")
        self.animations.addScanningEndAnimations(layer: self.centerPointLayer!, animationKey: "CenterPointLayerScanningEnd")
        
        self.animations.addAlertLayerAnimations(pointLayer: self.pointLayer!, polylineLayer: self.polylineLayer!, textLayer: self.textLayer!, pinyinLayer: self.pinyinLayer!)
    }
    
    func removeAniamtions() -> Void {
        
        self.parnentView?.layer.removeAllAnimations()
    }
    
    //MARK: 绘制篮圈
    
    func drawBlueLayer() -> Void {
        
        //绘制画布
        self.blueLayer = CALayer()
        let layerWidth = (_blueLayerRadius + _blueLayerWidth + _shadowRadius)
        self.blueLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                             y: _viewheight/2.0 - layerWidth,
                             width: layerWidth*2,
                             height: layerWidth*2)
        self.blueLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制弧线
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let arcShape = ArcShape(radius: _blueLayerRadius,
                             lineWidth: _blueLayerWidth,
                             opacity: 1.0,
                             fillColor: UIColor.clear,
                             strokeColor: kBlueLayerColor)
        
        let arcDegrees = [ArcDegree(fromDegree: -126, toDegree: 36),
                       ArcDegree(fromDegree: 54, toDegree: -144)]
        for arcDegree in arcDegrees {
            
            let shapeLayer = ARShapeLayer.addArcLayerAt(center: center,
                                                        degree: arcDegree,
                                                        shape: arcShape)
            addShadowToLayer(layer: shapeLayer)
            
//            self.blueLayer?.addSublayer(shapeLayer)
            ARShapeLayer.addGradientLayerTo(layer: self.blueLayer!, msakLayer: shapeLayer, colors: [kBlueLayerColor.cgColor, kBlue2LayerColor.cgColor])
        }
        
        //绘制小三角
        let triangleShape = TriangleShape(radius: _triangleLayerRadius,
                                          lineWidth: _triangleLayerWidth,
                                          opacity: 1.0,
                                          fillColor: kBlueLayerColor,
                                          strokeColor: kBlueLayerColor)
        
        
        let topTriangleCenter = getPointAtCircle(centerPoint: center, radius: _blueLayerRadius, angle: -135.0)
        let bottomTriangleCenter = getPointAtCircle(centerPoint: center, radius: _blueLayerRadius, angle: 45.0)
        let triangles = [TrianglePosition(centerPoint: topTriangleCenter, vertex1: 45.0, vertex2: 165.0, vertex3: 285.0),
                         TrianglePosition(centerPoint: bottomTriangleCenter, vertex1: -135.0, vertex2: -15.0, vertex3: 105.0)]
        for position in triangles {
            
            let shapeLayer = ARShapeLayer.addTriangleLayer(position: position, shape: triangleShape)
            
//            self.blueLayer?.addSublayer(shapeLayer)
            ARShapeLayer.addGradientLayerTo(layer: self.blueLayer!, msakLayer: shapeLayer, colors: [kBlueLayerColor.cgColor, kBlue2LayerColor.cgColor])
        }
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.blueLayer!)
    }
    
    //设置阴影
    func addShadowToLayer(layer: CALayer) -> Void {
        
        layer.shadowColor = UIColor.white.cgColor
        layer.shadowOpacity = 1.0
        layer.shadowRadius = 0.0
        layer.shadowOffset = CGSize.zero
    }
    
    //MARK: 绘制外圈
    
    func drawOutLayer() -> Void {
        
        //绘制画布
        self.outLayer = CALayer()
        let layerWidth = (_outLayerRadius + _outLayerWidth)
        self.outLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                                      y: _viewheight/2.0 - layerWidth,
                                      width: layerWidth*2,
                                      height: layerWidth*2)
        self.outLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制弧线
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let arcShape = ArcShape(radius: _outLayerRadius,
                                lineWidth: _outLayerWidth,
                                opacity: 0.4,
                                fillColor: UIColor.clear,
                                strokeColor: kWhiteLayerColor)
        
        let arcDegrees = [ArcDegree(fromDegree: -20, toDegree: 108),
                          ArcDegree(fromDegree: 160, toDegree: -70)]
        for arcDegree in arcDegrees {
            
            let shapeLayer = ARShapeLayer.addArcLayerAt(center: center,
                                                        degree: arcDegree,
                                                        shape: arcShape)
            self.outLayer?.addSublayer(shapeLayer)
        }
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.outLayer!)
    }
    
    //MARK: 绘制内圈
    
    func drawInlayer() -> Void {
        
        //绘制画布
        self.inLayer = CALayer()
        let layerWidth = (_inLayerRadius + _inLayerWidth2)
        self.inLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                                      y: _viewheight/2.0 - layerWidth,
                                      width: layerWidth*2,
                                      height: layerWidth*2)
        self.inLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制弧线
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let arcShape1 = ArcShape(radius: _inLayerRadius,
                                lineWidth: _inLayerWidth1,
                                opacity: 0.3,
                                fillColor: UIColor.clear,
                                strokeColor: UIColor.white)
        
        let arcShape2 = ArcShape(radius: _inLayerRadius,
                                 lineWidth: _inLayerWidth2,
                                 opacity: 1.0,
                                 fillColor: UIColor.clear,
                                 strokeColor: UIColor.white)
        
        let arcDegrees = [ArcDegree(fromDegree: -88, toDegree: 18),
                          ArcDegree(fromDegree: 32, toDegree: 138),
                          ArcDegree(fromDegree: 152, toDegree: 258),
                          
                          ArcDegree(fromDegree: -60, toDegree: -20),
                          ArcDegree(fromDegree: 60, toDegree: 100),
                          ArcDegree(fromDegree: 180, toDegree: 220)]
        
        var index: Int = 0
        var shape = arcShape1
        for arcDegree in arcDegrees {
            
            if index > 2 {
                shape = arcShape2
            }
            let shapeLayer = ARShapeLayer.addArcLayerAt(center: center,
                                                        degree: arcDegree,
                                                        shape: shape)
            self.inLayer?.addSublayer(shapeLayer)
            
            index += 1
        }
        
        //绘制弧线起点处小圆圈
        let circleCenter1 = getPointAtCircle(centerPoint: center, radius: _inLayerRadius, angle: 30)
        let circleCenter2 = getPointAtCircle(centerPoint: center, radius: _inLayerRadius, angle: 150)
        let circleCenter3 = getPointAtCircle(centerPoint: center, radius: _inLayerRadius, angle: -90)
        
        let centers = [circleCenter1, circleCenter2, circleCenter3]
        for center in centers {
            
            let shapeLayer = ARShapeLayer.addCircleLayer(centerPoint: center, radius: 1.5, opacity: 0.3, lineWidth: 1.0, isFill: false)
            self.inLayer?.addSublayer(shapeLayer)
        }
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.inLayer!)
    }
    
    //MARK: 绘制透明白圈
    
    func drawWhiteLayer() -> Void {
        
        //绘制画布
        self.whiteLayer = CALayer()
        let layerWidth = (_whiteLayerRadius + _whiteLayerWidth)
        self.whiteLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                                      y: _viewheight/2.0 - layerWidth,
                                      width: layerWidth*2,
                                      height: layerWidth*2)
        self.whiteLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制白圈
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let shapeLayer = ARShapeLayer.addCircleLayer(centerPoint: center, radius: _whiteLayerRadius, opacity: 0.1, lineWidth: _whiteLayerWidth, isFill: false)
        self.whiteLayer?.addSublayer(shapeLayer)
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.whiteLayer!)
    }
    
    //MARK: 绘制中心小圈
    
    func drawCenterCircle() -> Void {
        
        //绘制画布
        self.centerCircleLayer = CALayer()
        let layerWidth = (_centerCircleLayerRadius + 1.0)
        self.centerCircleLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                                      y: _viewheight/2.0 - layerWidth,
                                      width: layerWidth*2,
                                      height: layerWidth*2)
        self.centerCircleLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制弧线
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let arcShape = ArcShape(radius: _centerCircleLayerRadius,
                                lineWidth: 1.0,
                                opacity: 0.3,
                                fillColor: UIColor.clear,
                                strokeColor: UIColor.white)
        
        let arcDegrees = [ArcDegree(fromDegree: 3, toDegree: 87),
                          ArcDegree(fromDegree: 93, toDegree: 177),
                          ArcDegree(fromDegree: 183, toDegree: 267),
                          ArcDegree(fromDegree: 273, toDegree: 357)]
        for arcDegree in arcDegrees {
            
            let shapeLayer = ARShapeLayer.addArcLayerAt(center: center,
                                                        degree: arcDegree,
                                                        shape: arcShape)
            self.centerCircleLayer?.addSublayer(shapeLayer)
        }
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.centerCircleLayer!)
    }
    
    //MARK: 绘制中心小点
    
    func drawCenterPoint() -> Void {
        
        //绘制画布
        self.centerPointLayer = CALayer()
        let layerWidth = _centerPointLayerRadius
        self.centerPointLayer?.frame = CGRect(x: _viewWidth/2.0 - layerWidth,
                                        y: _viewheight/2.0 - layerWidth,
                                        width: layerWidth*2,
                                        height: layerWidth*2)
        self.centerPointLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制白圈
        let center = CGPoint(x: layerWidth, y: layerWidth)
        let shapeLayer = ARShapeLayer.addCircleLayer(centerPoint: center, radius: _centerPointLayerRadius, opacity: 1.0, lineWidth: 0.0, isFill: true)
        self.centerPointLayer?.addSublayer(shapeLayer)
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.centerPointLayer!)
    }
    
    //MARK: 绘制提示
    
    func drawAlertLayer(string: String) -> Void {
        
        //绘制画布
        self.alertLayer = CALayer()
        self.alertLayer?.frame = (self.parnentView?.bounds)!
        self.alertLayer?.backgroundColor = UIColor.clear.cgColor
        
        //绘制起点
        let startPoint = getPointAtCircle(centerPoint: (self.parnentView?.center)!, radius: (_outLayerRadius * 0.9), angle: -160)
        self.pointLayer = ARShapeLayer.addCircleLayer(centerPoint: startPoint, radius: _centerPointLayerRadius, opacity: 1.0, lineWidth: 0.0, isFill: true)
        self.pointLayer?.opacity = 0.0
        self.alertLayer?.addSublayer(self.pointLayer!)
        
        //绘制折线
        let middlePoint = CGPoint(x: (startPoint.x - cos(.pi/4)*20), y: (startPoint.y - cos(.pi/4)*20))
        let endPoint = CGPoint(x: middlePoint.x, y: (middlePoint.y - 60))
        self.polylineLayer = ARShapeLayer.addPolylineLayer(startPoint: startPoint, otherPoints: [middlePoint, endPoint])
        self.alertLayer?.addSublayer(self.polylineLayer!)
        
        //绘制文字
        let textFrame = CGRect(x: endPoint.x, y: (endPoint.y - 50), width: (_viewWidth - 2*endPoint.x), height: 30)
        self.textLayer = ARShapeLayer.addTextLayer(frame: textFrame, text: string, font: UIFont.systemFont(ofSize: 24.0))
        self.textLayer?.opacity = 0.0
        self.alertLayer?.addSublayer(self.textLayer!)
        
        let pinyinString = String(string.transformToPinYin())
        let pinyinFrame = CGRect(x: endPoint.x, y: (endPoint.y - 20), width: (_viewWidth - 2*endPoint.x), height: 20)
        self.pinyinLayer = ARShapeLayer.addTextLayer(frame: pinyinFrame, text: pinyinString.uppercased(), font: UIFont.systemFont(ofSize: 14.0))
        self.pinyinLayer?.opacity = 0.0
        self.alertLayer?.addSublayer(self.pinyinLayer!)
        
        //将画布添加到视图层
        self.parnentView?.layer.addSublayer(self.alertLayer!)
    }
}
